/**
 * 
 */
package com.appwx.sdk.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.util.Log;

/**
 * 文件缓存
 * @author xiajun
 * @see 硬盘读取速度当然不如内存，但是为了珍惜宝贵的流量，不让你的用户在月底没有流量时嚎叫着要删掉你开发的“流量杀手”，
 * 最好是避免重复下载。在第一次下载以后，将数据保存在本地即可。
 */
public class FileCache {

	private static final String TAG = FileCache.class.getSimpleName();
	
	private File cacheDir;
	
	/**
	 * Constructor
	 * @param context
	 */
	public FileCache(Context context,String cache_folder_name){
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			  cacheDir = new File(Environment.getExternalStorageDirectory(),cache_folder_name);
		}else{
			cacheDir = context.getCacheDir();
			if(!cacheDir.exists())
				cacheDir.mkdir();
		}
		Log.i(TAG, "cacheDir = " + cacheDir.getAbsolutePath());
	}
	
	/**
	 * 通过key获取文件
	 * @param key
	 * @return
	 */
	public File getFile(String key){
		File f = new File(cacheDir, key);
		if(f.exists()){
			Log.i(TAG, "the file you wanted exists " + f.getAbsolutePath());
			return f;
		}else{
			Log.i(TAG, "the file you wanted exists " + f.getAbsolutePath());
		}
		return null;
	}
	
	public void put(String key,Bitmap value){
		File f = new File(cacheDir,key);
		if(!f.exists()){
			try {
				f.createNewFile();
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(saveBitmap(f, value))
				Log.d(TAG, "Save file to sdcard successfully!");
			else
				Log.w(TAG, "Save file to sdcard failed!");
		}
	}
	
	/**
	 * 将Bitmap写入文件
	 * @param file
	 * @param bitmap
	 * @return
	 */
	public boolean saveBitmap(File file, Bitmap bitmap){
		if(file == null || bitmap == null)
			return false;
		try {
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
			return bitmap.compress(CompressFormat.JPEG, 100, out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 清除缓存目录的sd卡
	 */
	public void clear(){
		File[] files = cacheDir.listFiles();
		for (File file : files) {
			file.delete();
		}
	}
}
